package main

import (
	"database/sql"
	_ "github.com/lib/pq"
	"fmt"
	"github.com/snluu/uuid"
	"strings"
)

//type xx struct {
//	id string
//	name string
//}

var db *sql.DB

func sqlOpen()  {
	var err error
	//port是数据库的端口号，默认是5432，如果改了，这里一定要自定义；
	//user就是你数据库的登录帐号;
	//dbname就是你在数据库里面建立的数据库的名字;
	//sslmode就是安全验证模式;
	db1, err := sql.Open("postgres","host=47.94.167.248 port=5432 user=postgres password=postgres dbname=goxx sslmode=disable ")
	//还可以是这种方式打开
	//db1, err := sql.Open("postgres", "postgres://postgres:postgres@47.94.167.248/goxx?sslmode=verify-full")

	db = db1
	checkErr(err)
}

func UUID() string {
	return strings.Replace(uuid.Rand().Hex(),"-","",-1)
}

func sqlInsert() {
	//插入数据
	stmt, err := db.Prepare("INSERT INTO xx(id,name,age) VALUES($1,$2,$3) RETURNING id")
	checkErr(err)

	res, err := stmt.Exec(UUID(), "testx22xx",2)
	//这里的三个参数就是对应上面的$1,$2,$3了

	checkErr(err)

	affect, err := res.RowsAffected()
	checkErr(err)

	fmt.Println("rows affect:", UUID(), affect)
}

func sqlClose() {
	db.Close()
}

func checkErr(err error) {
	if err != nil {
		panic(err)
	}
}

func sqlSelect() {
	//查询数据
	rows, err := db.Query("SELECT * FROM xx")
	checkErr(err)

	println("-----------")
	for rows.Next() {
		var id string
		var name string
		var age int
		err = rows.Scan(&id, &name,&age)
		checkErr(err)
		fmt.Println("id = ", id, "name = ",name, "age = ", age)
	}
}

func test()  {
	sqlOpen()

	//sqlInsert()
	sqlSelect()

	sqlClose()
}

func main() {
	test()
	//fmt.Println(UUID())
}
